package com.systemCapacity.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.systemCapacity.common.lang.Result;
import com.systemCapacity.entity.User;
import com.systemCapacity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author 任杰
 * @since 2023.6.15
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final int ONLINE = 1;

    private static final int OFFLINE = 2;

    @Autowired
    UserService userService;

    /**
     * 查询特定用户
     * @param id 用户id
     * @return 查询结果
     */
    @GetMapping("/index/{id}")
    public Result index(@PathVariable(name = "id") long id) {
        User user = userService.getById(id);
        return Result.succ(user);
    }

    /**
     * 保存用户
     * @param user 用户结构
     * @return 保存结果
     */
    @PostMapping("/save")
    public Result saveUser(@Validated @RequestBody User user) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
        if (userService.userNameExist(user.getUsername())) {
            return Result.fail("用户名称已存在", null);
        }
        user.setCreatedUser("admin");
        user.setCreatedTime(LocalDateTime.now());
        user.setStatus(OFFLINE);
        try {
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("新增用户失败");
        }
        return Result.succ(user);
    }

    /**
     * 删除用户
     * @param userId 用户id
     * @return 删除结果
     */
    @GetMapping("/delete/{id}")
    public Result deleteUser(@PathVariable(name = "id") Long userId) throws Exception{

        // 查询user是否存在
        if (!userService.userExist(userId)) {
            return Result.fail("该用户不存在,请确认要删除的用户是否正确");
        }
        try {
            userService.removeById(userId);
        } catch (Exception e) {
            return Result.fail("删除用户失败");
        }
        return Result.succ(null);
    }

    /**
     * 查看用户列表
     * @param request 查询请求
     * @return 用户列表
     * @throws Exception 解析请求错误
     */
    @GetMapping("/list")
    public Result getUsers(HttpServletRequest request) throws Exception{
        IPage<User> userPage = userService.getUserPage(request);
        return Result.succ(userPage);
    }

    /**
     * 编辑用户
     * @param user 用户结构
     * @return 编辑结果
     * @throws Exception 解析异常
     */
    @PostMapping("/edit")
    public Result editUser(@RequestBody User user) throws Exception{
        Assert.notNull(user.getId(), "用户不能为空");

        if (!userService.userExist(user.getId())) {
            return Result.fail("当前用户不存在，请重新选择要修改的用户");
        }

        Assert.notNull(user.getPassword(), "用户密码不能为空");
        // 修改密码
        user.setPassword(user.getPassword());
        // 修改修改时间以及修改人
        user.setUpdatedUser("admin");
        user.setUpdatedTime(LocalDateTime.now());

        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userLambdaUpdateWrapper.eq(User::getId, user.getId())
                .set(User::getPassword, user.getPassword())
                .set(User::getUpdatedUser, "admin")
                .set(User::getUpdatedTime, LocalDateTime.now());
        try {
            userService.update(userLambdaUpdateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("更新用户失败");
        }
        return Result.succ(null);
    }
}
